from Core.exception import *
from Site.controller import auth
from Site.controller.messages import *

import requests


def get_ctx(request, subtitle='PassNote'):
    ctx = {
        'subtitle': subtitle,
        'poem': requests.get('http://cloud.deali.cn/poem.php').content.decode('utf-8'),
        'platforms': get_platform(request)
    }

    msg = get_global_msg(request)
    if msg is not None:
        ctx['global_message'] = msg

    try:
        session = auth.cookie_verify(request)
        ctx['session_id'] = session.id
        ctx['session'] = session
        ctx['user_info'] = session.user
        ctx['verify'] = True
    except NoCookiesProvide as e:
        ctx['message'] = Message('Please login first!', MessageType.danger)
        ctx['verify'] = False
    except Exception as e:
        ctx['message'] = Message(e, MessageType.alert)
        ctx['verify'] = False

    return ctx


def get_verify(request):
    ctx = get_ctx(request)
    return ctx['verify']


def get_account(request, id):
    """根据账户ID获取指定账户"""
    session = auth.cookie_verify(request)
    accounts = session.user.accounts
    account = accounts.filter(id=id)
    if account.exists():
        return account.first()
    else:
        return None


def get_accounts(request, platform_name):
    """根据平台名称获取账户列表"""
    session = auth.cookie_verify(request)
    accounts = session.user.accounts
    platform = session.user.account_platforms.filter(name=platform_name)
    if platform.exists():
        platform = platform.first()
        return accounts.filter(platform=platform)
    else:
        return None


def get_platform(request):
    try:
        platforms = {
            'platform name': {
                'name': 'platform name',
                'description': 'platform description',
                'accounts': []
            }
        }
        platforms = dict()

        session = auth.cookie_verify(request)
        accounts = session.user.accounts

        for p in session.user.account_platforms.all():
            platforms[p.name] = dict()
            platforms[p.name]['name'] = p.name
            platforms[p.name]['description'] = p.description
            platforms[p.name]['accounts'] = accounts.filter(platform=p)

        return platforms
    except NoCookiesProvide as e:
        return None
    except Exception as e:
        set_global_msg(request, e, 'danger')
        return None
